package cn.acmoj.oj.controller;

import cn.acmoj.oj.bean.Contest;
import cn.acmoj.oj.bean.Problem;
import cn.acmoj.oj.bean.Solution;
import cn.acmoj.oj.bean.User;
import cn.acmoj.oj.service.ContestService;
import cn.acmoj.oj.service.ProblemSetService;
import cn.acmoj.oj.service.SolutionService;
import cn.acmoj.oj.service.UserService;
import cn.acmoj.oj.util.Util;
import com.sun.xml.internal.bind.v2.TODO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * cn.acmoj.oj.controller
 * Springer
 * 2017-11-22
 */
@Controller
@RequestMapping(value = "contest")
public class ContestProblemSetController {

    @Resource
    private ProblemSetService problemSetService;
    @Resource
    private ContestService contestService;
    @Resource
    private SolutionService solutionService;

    @RequestMapping(value = "problemset", method = RequestMethod.GET)
    public String problemSet(@RequestParam(required = false, defaultValue = "-1") Integer cid,
                             HttpSession session,
                             HttpServletRequest request) {
        if (cid != null && cid == -1) {
            cid = (Integer) session.getAttribute("cid");
        }
        if (cid == null) {
            return "contest/error";
        }
        //TODO 2018年3月3日22:52:47 密码、权限拦截
        Contest contest = contestService.getOnce(cid);
        User user = (User) session.getAttribute("user");
        List<Integer> list_s = new ArrayList<>();
        if (contest == null) {
            return "contest/error";
        }

        List<Problem> list;
        if (contest.getStart_time().after(new Timestamp(System.currentTimeMillis()))) {
            if (user == null
                    || session.getAttribute("privilege") == null
                    || !session.getAttribute("privilege").equals("administrator")
                    ) {
                list = new ArrayList<>();
            } else {
                list = problemSetService.getAllContestProblem(cid);
            }
        } else {
            list = problemSetService.getAllContestProblem(cid);
        }
        if (user != null) {
            int finalCid = cid;
            list.forEach(problem -> list_s.add(
                    solutionService.isAccepted(
                            problem.getProblem_id(),
                            user.getUser_id(),
                            finalCid
                    )
            ));
        }
        request.setAttribute("contest", contest);
        request.setAttribute("list", list);
        request.setAttribute("list_s", list_s);
        return "contest/contest";
    }

}
